/**
 * iOS Strings 格式生成器
 * 生成 .strings 和 .stringsdict 文件
 */
class StringsGenerator {
  static async generate(data, platform = "ios") {
    if (!data || typeof data !== "object") {
      throw new Error("数据必须是一个对象");
    }

    let result = "";

    // 添加文件头注释
    result += this.generateHeader();

    // 对键进行排序
    const sortedKeys = Object.keys(data).sort();

    for (const key of sortedKeys) {
      const value = data[key];

      // 转义特殊字符
      const escapedValue = this.escapeValue(value);

      // 生成键值对
      result += `"${key}" = "${escapedValue}";\n`;
    }

    return result;
  }

  static generateHeader() {
    const now = new Date().toISOString();
    return `/*
  Localizable.strings
  Generated by i18n-CLI
  
  Created on ${now}
*/

`;
  }

  static escapeValue(value) {
    if (typeof value !== "string") {
      return String(value);
    }

    return value
      .replace(/\\/g, "\\\\") // 反斜杠
      .replace(/"/g, '\\"') // 双引号
      .replace(/\n/g, "\\n") // 换行符
      .replace(/\r/g, "\\r") // 回车符
      .replace(/\t/g, "\\t") // 制表符
      .replace(/%/g, "%%"); // 百分号（如果不是格式化字符串的话）
  }

  static generateStringsDict(data, platform = "ios") {
    // 生成 .stringsdict 格式（用于复数形式）
    let result = `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
`;

    const sortedKeys = Object.keys(data).sort();

    for (const key of sortedKeys) {
      const value = data[key];

      result += `\t<key>${key}</key>
\t<dict>
\t\t<key>NSStringLocalizedFormatKey</key>
\t\t<string>%#@value@</string>
\t\t<key>value</key>
\t\t<dict>
\t\t\t<key>NSStringFormatSpecTypeKey</key>
\t\t\t<string>NSStringPluralRuleType</string>
\t\t\t<key>NSStringFormatValueTypeKey</key>
\t\t\t<string>d</string>
\t\t\t<key>other</key>
\t\t\t<string>${this.escapeXml(value)}</string>
\t\t</dict>
\t</dict>
`;
    }

    result += `</dict>
</plist>`;

    return result;
  }

  static escapeXml(value) {
    if (typeof value !== "string") {
      return String(value);
    }

    return value
      .replace(/&/g, "&amp;")
      .replace(/</g, "&lt;")
      .replace(/>/g, "&gt;")
      .replace(/"/g, "&quot;")
      .replace(/'/g, "&#39;");
  }
}

module.exports = StringsGenerator;
